package com.codemeta.bokit.web.config;

import com.codemeta.bokit.web.core.filter.WebFilterOrder;
import com.codemeta.bokit.web.core.filter.CacheRequestBodyFilter;
import com.codemeta.bokit.web.core.filter.XssFilter;
import com.codemeta.bokit.props.WebProps;
import com.codemeta.bokit.props.WebXssProps;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.util.PathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * web组件自动装配
 *
 * @author hice
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({WebProps.class, WebXssProps.class})
public class WebAutoConfig implements WebMvcConfigurer {

    // ========== Filter 相关 ==========

    /**
     * 创建 CorsFilter Bean，解决跨域问题
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean() {
        // 创建 CorsConfiguration 对象
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        // 创建 UrlBasedCorsConfigurationSource 对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return createFilterBean(new CorsFilter(source), WebFilterOrder.CORS_FILTER);
    }

    /**
     * 创建 RequestBodyCacheFilter Bean，可重复读取请求内容
     */
    @Bean
    public FilterRegistrationBean<CacheRequestBodyFilter> cacheRequestBodyFilter() {
        log.debug("【bokit】开启CacheRequestBodyFilter可重复读取请求过滤器");
        return createFilterBean(new CacheRequestBodyFilter(), WebFilterOrder.REQUEST_BODY_CACHE_FILTER);
    }

    /**
     * 创建 XssFilter Bean，解决 Xss 安全问题
     */
    @Bean
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    public FilterRegistrationBean<XssFilter> xssFilter(WebXssProps props, PathMatcher pathMatcher) {
        log.debug("【bokit】开启XssFilter安全过滤器");
        return createFilterBean(new XssFilter(props, pathMatcher), WebFilterOrder.XSS_FILTER);
    }

    /**
     * 快速失败模式
     *
     * @return .
     * @apiNote SpringValidation默认会校验完所有字段，然后才抛出异常。通过配置开启Fail-Fast模式，一旦校验失败就立即返回。
     */
    @Bean
    public Validator validator() {
        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class).configure().failFast(true)
            .buildValidatorFactory();
        return factory.getValidator();
    }

    // ========== 私有方法 ==========

    private static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, WebFilterOrder order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order.getValue());
        return bean;
    }

    private List<MediaType> getMediaType() {
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        return mediaTypes;
    }

}